const WebSocket = require('ws');

// WebSocket 状态:
// CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3

class WsClient {
    constructor(url) {
        this.url = url;
        this.reconnectInterval = 5000;
        this.heartbeatInterval = 30000; // 30 秒发送一次心跳
        this.heartbeatTimer = null;
        this.socket = null;
        this.connect();
    }

    connect() {
        this.socket = new WebSocket(this.url);

        this.socket.onopen = () => {
            console.log('✅ WebSocket 已连接');
            this.startHeartbeat();
            if (this.onOpen) this.onOpen();
        };

        this.socket.onmessage = (event) => {
            // 过滤服务端心跳回应可选
            if (event.data === 'pong') return;
            if (this.onMessage) this.onMessage(event.data);
        };

        this.socket.onclose = () => {
            console.log('❌ 连接关闭，尝试重连...');
            this.stopHeartbeat();
            setTimeout(() => this.connect(), this.reconnectInterval);
        };

        this.socket.onerror = (err) => {
            console.error('⚠️ 连接错误:', err);
        };
    }

    send(data) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(data));
        } else {
            console.warn('⚠️ 无法发送，连接未就绪');
        }
    }

    startHeartbeat() {
        this.stopHeartbeat(); // 避免重复启动
        this.heartbeatTimer = setInterval(() => {
            if (this.socket.readyState === WebSocket.OPEN) {
                this.socket.send('ping');
            }
        }, this.heartbeatInterval);
    }

    stopHeartbeat() {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        }
    }

    setOnMessage(handler) {
        this.onMessage = handler;
    }

    setOnOpen(handler) {
        this.onOpen = handler;
    }

    close() {
        this.socket.close()
    }
}

module.exports = WsClient;
